#include "qfaultmanager.h"

#include "xmlobject.h"

#include <QFile>
#include <QApplication>

QFaultManager::QFaultManager(QObject *parent) :
    QObject(parent)
{
}

QFaultManager::~QFaultManager()
{
    qDeleteAll(m_faults);
    m_faults.clear();
}

QList<tagFaultInfo*> QFaultManager::get_faults()
{
    return m_faults;
}

void QFaultManager::add_fault(const tagFaultInfo &fault)
{
    tagFaultInfo* info=new tagFaultInfo;
    info->m_code=fault.m_code;
    info->m_time=fault.m_time;
    m_faults.append(info);
}

void QFaultManager::remove_fault(int index)
{
    delete m_faults.takeAt(index);
}

void QFaultManager::remove_fault(tagFaultInfo *info)
{
    if(m_faults.contains(info))
    {
        m_faults.removeAll(info);
        delete info;
    }
}

void QFaultManager::clear_fault()
{
    qDeleteAll(m_faults);
    m_faults.clear();
}

void QFaultManager::load()
{
    clear_fault();

    QFile f(qApp->applicationDirPath()+"/data/fault.xml");

    if(!f.open(QFile::ReadWrite))
    {
        return ;
    }

    QString str=f.readAll();

    f.close();

    XMLObject xml;

    if(!xml.load(str,0))
    {
        return;
    }

    QList<XMLObject*> list=xml.get_children();

    foreach(XMLObject* o,list)
    {
        tagFaultInfo *info=new tagFaultInfo;
        info->m_code=o->get_property("code").toInt();
        info->m_time=o->get_property("time");
        m_faults.append(info);
    }
}

void QFaultManager::save()
{
    QFile f(qApp->applicationDirPath()+"/data/fault.xml");

    if(!f.open(QFile::ReadWrite))
    {
        return ;
    }

    f.resize(0);


    XMLObject xml;

    xml.set_title("Faults");

    foreach(tagFaultInfo *info,m_faults)
    {
        XMLObject *o=new XMLObject(&xml);
        o->set_title("Fault");
        o->set_property("time",info->m_time);
        o->set_property("code",QString::number(info->m_code));
    }

    QString str=xml.write();

    f.write(str.toLocal8Bit());
    f.close();
}
